/*
 * @Author: xiaosihan 
 * @Date: 2022-02-15 16:08:43 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2022-02-15 16:21:38
 */
/*
 * @Author: xiaosihan 
 * @Date: 2021-12-21 09:52:52 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2022-02-15 14:50:41
 */

import ApngTexture from "three-base/ApngTexture";
import { WebGLRenderer } from "three";
import SpriteText from "three-base/SpriteText";
import SubBtn3DBgPNG from "./SubBtn3D.png";

export default class SubBtn3D extends SpriteText {

    constructor(text?: string) {
        super(SubBtn3D.completion(text));
        this.borderColor = "#ff0";
        this.borderWidth = 0;
        this.borderRadius = 0;

        this.fontSize = 60;
        this.padding = 10;

        this.init();
    }

    static frame = 0;

    customScale = 1;

    // 动态背景纹理
    static btnBg = new ApngTexture(SubBtn3DBgPNG);

    // 使用空格补全字符长度
    static completion(text: string = "") {
        const textLength = text.length;
        const spaceLength = Math.ceil((10 - textLength) * 2);
        const space = new Array(spaceLength).fill(" ").join("");
        return `${space}${text}${space}`;
    }

    init() {
        this.material.alphaTest = 0.01;
    }

    _genCanvas() {
        // @ts-ignore
        super._genCanvas();

        //@ts-ignore
        const canvas = this._canvas as HTMLCanvasElement;
        const { width: btnBgWidth, height: btnBgHeight } = SubBtn3D.btnBg.image;
        const { width, height } = canvas;
        const ctx = canvas.getContext("2d")!;
        ctx.globalCompositeOperation = "destination-over";
        ctx.fillStyle = "#ff0000";
        ctx.globalAlpha = 1;
        ctx.setTransform(1, 0, 0, 1, 0, 0);
        ctx.drawImage(SubBtn3D.btnBg.image, 150, 20, btnBgWidth - 260, btnBgHeight - 40, 0, 0, width, height);
    }

    // cursor = "pointer";

    onClick?: () => void;

    renderOrder = 9;

    onBeforeRender = (renderer: WebGLRenderer) => {

        const frame = renderer.info.render.frame;

        if (SubBtn3D.frame !== frame) {
            SubBtn3D.frame = frame;
            SubBtn3D.btnBg.onUpdate();
        }

        this._genCanvas();
        this.scale.multiplyScalar(this.customScale);

    }

}

